﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core.Config;
using TouchSocket.Rpc.TouchRpc;
using TouchSocket.Sockets;
using RRQMProxy;
using System.IO;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;

namespace Updater.Core
{
    /// <summary>
    /// 给应用的客户端使用，用于获取升级的版本信息。
    /// </summary>
    public static class VersionHelper
    {
      /// <summary>
      /// 获取当前客户端版本号
      /// </summary>
      /// <returns></returns>
        public static int GetCurrentVersion()
        {
            //1.先判断文件是否存在
            if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "AutoUpdater\\UpdateConfiguration.xml"))
            {
                //不存在则新建一个文件
                UpdateConfiguration updateConfiguration = new UpdateConfiguration();
                updateConfiguration.Save(AppDomain.CurrentDomain.BaseDirectory + "AutoUpdater\\UpdateConfiguration.xml");
            }
            string path = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdater\\UpdateConfiguration.xml";
            UpdateConfiguration config = FastJson.Load<UpdateConfiguration>(path);

            return config.ClientVersion;
        }
       
        /// <summary>
        /// 从服务端获得最新客户端的版本号。
        /// </summary>
        /// <param name="ServerIP">服务端的IP</param>
        /// <param name="ServerPort">服务端的端口</param>        
        public static int GetLatestVersion(string ServerIP, int ServerPort)
        {
            /*
            Random random = new Random();
            string userid = random.Next(1000000).ToString("00000");
            IRapidPassiveEngine rapidPassiveEngine = RapidEngineFactory.CreatePassiveEngine();
            ESPlus.Application.Basic.LogonResponse logonResponse = rapidPassiveEngine.Initialize(userid, "", oausServerIP, oausServerPort, null);
            rapidPassiveEngine.Close();
            return int.Parse(logonResponse.FailureCause);
            */
            TcpTouchRpcClient client = new TcpTouchRpcClient();
            client.Setup(new TouchSocketConfig()
                .SetRemoteIPHost(ServerIP.ToString()+":"+ServerPort.ToString())
                .SetVerifyToken("TouchRpc"));
            client.Connect();

            UpRpcServer myRpcServer = new UpRpcServer(client);//MyRpcServer类是由代码工具生成的类。

            //代理调用时，基本和本地调用一样。只是会多一个调用配置参数。
            int result = myRpcServer.GetLatestVersion(InvokeOption.WaitInvoke);
            

            client.SafeDispose();//client是长连接，可以复用，但在此处使用短连接。

            return result;
            
        }

        /// <summary>
        /// 是否有新版本？
        /// </summary>
        /// <param name="ServerIP">服务端的IP</param>
        /// <param name="ServerPort">服务端的端口</param>        
        public static bool HasNewVersion(string ServerIP, int ServerPort)
        {
            try
            {
                Console.WriteLine(VersionHelper.GetLatestVersion(ServerIP, ServerPort));
                
                return VersionHelper.GetLatestVersion(ServerIP, ServerPort) != VersionHelper.GetCurrentVersion();
            }
            catch (Exception)
            {

               return false;
            }
            
        }
 
        /// <summary>
        /// 判断某个端口是否启用
        /// </summary>
        /// <param name="Port"></param>
        /// <returns></returns>
        public static bool PortInUse(int Port)
        {
            bool re = false;
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] iPEndPoints=ipProperties.GetActiveTcpListeners();
            foreach (var item in iPEndPoints)
            {
                if (item.Port==Port)
                {
                    re=true;
                    break;
                }
            }
            return re;
        }
        /// <summary>
        /// 自动检测更新,会抛出异常
        /// </summary>
        public static void AotuRun()
        {
            try
            {
                
                
                if (VersionHelper.HasNewVersion(Dns.GetHostAddresses("www.zcjz.top")[0].ToString(), 4000))
                {
                    string updateExePath = AppDomain.CurrentDomain.BaseDirectory + "AutoUpdater\\Updater.exe";
                    System.Diagnostics.Process myProcess = System.Diagnostics.Process.Start(updateExePath);
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch (Exception e)
            {
                throw e;
                
            }
           
        }

    }
}
